﻿using System.Collections.Generic;
using System.Linq;
using RimWorld;
using UnityEngine;
using Verse;
using static UnityEngine.GraphicsBuffer;

namespace ARMIR {
    public class HediffComp_lockedPawn : HediffComp{
        public HediffCompProperties_lockedPawn Props => (HediffCompProperties_lockedPawn)props;
        //流程控制
        private int ticksToNextEffecter; //每次显示线段所需tick
        private int gapToNextChange;  //每次变换效果状态累计计数
        private int tickDisappear; //离开技能范围后效果消失间隔
        //连线Pawns
        private List<Pawn> linkPawns;
        private float disappearDistance = 32; //TD效果消失的距离
        //方框状态
        private Vector3 positionOffset; //方框坐标偏差
        private float sizeBlock; //方框的长度
        private float heightBlock; //方框高度
        private Vector2 growthDirection; //增长方向
        private bool crossLine; //是否存在十字

        //初始化
        public override void CompPostMake()
        {
            base.CompPostMake();
            ticksToNextEffecter = Props.ticksToNextEffecter;
            gapToNextChange = 0;
            linkPawns = new List<Pawn>();
            //概率存在十字装饰
            if (UnityEngine.Random.value > 0.8) { 
                crossLine = true;
            }else {
                crossLine= false;
            }
        }
        public override void CompPostTick(ref float severityAdjustment)
        {
            base.CompPostTick(ref severityAdjustment);
            // 只在pawn存活且在地图上时生效
            if (Pawn.Dead || Pawn.Map == null) return;
            // 倒计时触发效果
            ticksToNextEffecter--;
            if (ticksToNextEffecter <= 0)
            {
                tryTriggerEffecter();
                ticksToNextEffecter = Props.ticksToNextEffecter;
                gapToNextChange++;
            }
            //检查被锁定者是否依旧在技能范围内
            lockedInRange();
            if (tickDisappear != 0) { 
                //渲染方框
                if (positionOffset != null) {
                    changingBlock();
                }
                //渲染线条
                if (linkPawns.Any())
                {
                    linkLines();
                }
            }
            if (tickDisappear <= Props.tickDisappear && tickDisappear != 0) { 
                
            }
            //累计触发特效变化
            if (gapToNextChange >= Props.gapToNextChange && UnityEngine.Random.value >= 0.8f) { //大于指定间隔且概率判定过关执行变化(20%概率)
                changeEffecter(); //变换效果
                gapToNextChange = 0; //重置计时
            }
        }
        
        //周期性触发效果
        private void tryTriggerEffecter() {
            //测试用Effecter标记
            //EffecterDef shieldEffecter = Props.effecter;
            //shieldEffecter.SpawnAttached(Pawn, Pawn.Map);
            //设置连线Pawns
            linkPawns.Clear();
            var enemies = Pawn.Map.mapPawns.AllPawnsSpawned.Where(p => p.health.hediffSet.HasHediff(Props.linkHediff) && 
            p.Position.DistanceTo(Pawn.Position) <= 8).ToList(); //挑选目标5格范围内同样被标记的Pawn为列表
            int linkCount = Random.Range(0, 2); //随机与范围内0~5位同样被标记的Pawn连线
            for (int i = 0; i <= linkCount; i++) { //选择linkCount数量的随机pawn加入linkPawns
                int randomChoice = Random.Range(0, enemies.Count);
                linkPawns.Add(enemies[randomChoice]);
            }
        
        }
        //变化效果
        private void changeEffecter() {
            //随机生成方框中心
            var oriCell = new Vector3(Random.Range(-0.2f,0.2f), 0, Random.Range(-0.2f,0.2f));
            positionOffset = oriCell;
            //随机生成方框长宽
            sizeBlock = Random.Range(0.5f, 0.8f);
            heightBlock = Random.Range(1f, 1.4f);
            //随机生成增长方向
            growthDirection = new Vector2(Random.Range(-0.01f, 0.01f), Random.Range(-0.01f, 0.01f));
        }
        //渲染持续变化的Block
        private void changingBlock() {
            //渲染方框
            var PawnPosition = Pawn.Position;
            var displayPosition = new Vector3(PawnPosition.x + positionOffset.x + 0.5f, PawnPosition.y + positionOffset.y, PawnPosition.z + positionOffset.z + 0.5f);
            //如果在范围外则显示X框
            if (tickDisappear == Props.tickDisappear) {
                ARMIR_Draw.DrawWhiteHollowBlock(displayPosition, sizeBlock, heightBlock, false, 0.05f);
            }else {
                crossLine = false;
                ARMIR_Draw.DrawWhiteHollowBlock(displayPosition, sizeBlock, heightBlock, true, 0.05f);
            }
            //方框增长
            sizeBlock += growthDirection.x;
            heightBlock += growthDirection.y;
            //渲染十字装饰
            if (crossLine) {
                ARMIR_Draw.DrawCrossLine(displayPosition, sizeBlock / 2f);
            }
        }
        //渲染线条
        private void linkLines() {
            foreach (var p in linkPawns) {
                Material lineMat = SolidColorMaterials.SimpleSolidColorMaterial(new Color(1f, 1f, 1f, 1f)); //白线
                var startLine = new Vector3(Pawn.Position.ToVector3().x + 0.5f, Pawn.Position.ToVector3().y, Pawn.Position.ToVector3().z + 0.5f);
                var endLine = new Vector3(p.Position.ToVector3().x + 0.5f, p.Position.ToVector3().y, p.Position.ToVector3().z + 0.5f);
                GenDraw.DrawLineBetween(startLine, endLine,lineMat,0.05f); //渲染线
            }
        }
        //检查被锁定者是否在技能范围内
        private void lockedInRange() { 
            //拿到地图上正在释放asYourWish的在范围内的角色
            var possibleAbilityUser = Pawn.Map.mapPawns.AllPawnsSpawned.Where(
            p => p.health.hediffSet.HasHediff(DefDatabase<HediffDef>.GetNamed("ARMIR_AsYourWishHediff")) &&
            p.Position.DistanceTo(Pawn.Position) <= disappearDistance).ToList();
            //存在则重置计时
            if (possibleAbilityUser.Any()) {
                tickDisappear = Props.tickDisappear;
            }else {
                //范围外开始倒计时
                if (tickDisappear > 0) { 
                    tickDisappear--;
                }

            }
            //如果地图上完全没有技能释放者且计时完毕，则清除锁定hediff(该Hediff)
            var noOneUsingAbility = Pawn.Map.mapPawns.AllPawnsSpawned.Where(p => p.health.hediffSet.HasHediff(DefDatabase<HediffDef>.GetNamed("ARMIR_AsYourWishHediff"))).ToList();
            if (!noOneUsingAbility.Any() && tickDisappear == 0) {
                Pawn.health.RemoveHediff(parent);
            }

        }

    }

}


